function [dataSMM,resCS] = momentsSMM(data,dataCSreg,nyMom,CSregress_m,SMMwithCSreg)

% "data" is the data set for filtering. Here we use moments for the first nyMom series
if SMMwithCSreg == 2
    % Include CS moments and risk adjusted CS moments
    dataUsed  = [data(CSregress_m+1:end,1:nyMom) data(CSregress_m+1:end,1:nyMom).^2];
elseif SMMwithCSreg == 1
    % Include CS moments
    dataUsed  = [data(CSregress_m+1:end,1:nyMom) data(CSregress_m+1:end,1:nyMom).^2];
elseif SMMwithCSreg == 0
    dataUsed  = [data(1:end,1:nyMom) data(1:end,1:nyMom).^2];
end
dataMoments_v1 = mean(dataUsed,1);

% The co-variances for CS regressions
% Which maturities to select
%select         = [3 5 7 10]*4/CSregress_m;
select         = [2:10]*4/CSregress_m;
maturities_CS  = select*CSregress_m;
if SMMwithCSreg == 2
    % Including CS moments and adjusted CS moments
    resCS = CampbellSchillerRegression(dataCSreg,CSregress_m);
    
    % Moment conditions for ordinary CS regressions (centered)
    T              = size(resCS.Ydata,1);
    tmp_yx         = (resCS.Ydata(1:end,select)-repmat(mean(resCS.Ydata(1:end,select),1),T,1)).*resCS.Xdata(1:end,select);
    tmp_xx         = (resCS.Xdata(1:end,select)-repmat(mean(resCS.Xdata(1:end,select),1),T,1)).*resCS.Xdata(1:end,select);
    %check: mean(tmp_1,1)./mean(tmp_2,1)
    % Moment conditions for risk-adjusted CS regressions (centered)
    tmp_yx_adjust  = tmp_xx;
    dataMoments_v2 = mean([tmp_yx,tmp_xx,tmp_yx_adjust],1);
    
    % Collecting the moments
    dataMoments     = [dataMoments_v1 dataMoments_v2];
    dataMoments_mat = [dataUsed(:,1:nyMom) dataUsed(:,1:nyMom).^2 tmp_yx tmp_xx tmp_yx_adjust];
    
elseif SMMwithCSreg == 1
    % Including CS moments
    resCS = CampbellSchillerRegression(dataCSreg,CSregress_m);
        
    % Moment conditions for CS regressions (centered)
    T              = size(resCS.Ydata,1);
    tmp_yx         = (resCS.Ydata(1:end,select)-repmat(mean(resCS.Ydata(1:end,select),1),T,1)).*resCS.Xdata(1:end,select);
    tmp_xx         = (resCS.Xdata(1:end,select)-repmat(mean(resCS.Xdata(1:end,select),1),T,1)).*resCS.Xdata(1:end,select);
    dataMoments_v2 = mean([tmp_yx,tmp_xx],1);
    
    % Collecting the moments
    dataMoments     = [dataMoments_v1 dataMoments_v2];
    dataMoments_mat = [dataUsed(:,1:nyMom) dataUsed(:,1:nyMom).^2 tmp_yx tmp_xx];
elseif SMMwithCSreg == 0
    % Including CS moments
    resCS = CampbellSchillerRegression(dataCSreg,CSregress_m);
    
    dataMoments     = dataMoments_v1;
    dataMoments_mat = [dataUsed(:,1:nyMom) dataUsed(:,1:nyMom).^2];
end

% Removing first moment for mean of hours and wages (are zero)
dataMoments     = dataMoments(1,3:end);
dataMoments_mat = dataMoments_mat(:,3:end);
% Save results
dataSMM.dataMoments     = dataMoments;
dataSMM.dataMoments_mat = dataMoments_mat;
dataSMM.maturities_CS   = maturities_CS;
end

